package br.com.comanda.dao.helper.versionControl;

import java.util.List;

import br.com.comanda.util.CollectionUtils;

/**
 * Classe para cuidar do controle de upgrades realizados na base de dados
 * 
 * @author thiago
 * @since 09/01/2013
 */
public class VersionControl {

	private List<DatabaseUpgrade> list;

	public VersionControl() {
		/*
		 * DatabaseUpgrade upgrade1 = new DatabaseUpgrade();
		 * upgrade1.setDate("27/03/2012"); upgrade1.setDatabaseVersion(12);
		 * upgrade1.setSqlCommand(
		 * "ALTER TABLE MERCADORIA ADD COLUMN ID_GRUPO_CATALOGO INTEGER;");
		 * 
		 * DatabaseUpgrade upgrade2 = new DatabaseUpgrade();
		 * upgrade2.setDate("27/03/2012"); upgrade2.setDatabaseVersion(12);
		 * upgrade2.setSqlCommand("DROP TABLE IF EXISTS GRUPO_EXCLUSIVO;");
		 * 
		 * list = Arrays.asList(upgrade1, upgrade2);
		 */
	}

	public boolean existsNewUpgrade(int oldVersion) {
		if (!CollectionUtils.isEmpty(list)) {
			for (DatabaseUpgrade upgrade : list) {
				if (upgrade.getDatabaseVersion() > oldVersion) {
					return true;
				}
			}
		}

		return false;
	}

	public List<DatabaseUpgrade> getUpgradesToExecute(int oldVersion,
			int newVersion) {
		if (!CollectionUtils.isEmpty(list)) {
			for (int i = 0; i < list.size(); i++) {
				DatabaseUpgrade upgrade = list.get(i);

				if (upgrade.getDatabaseVersion() > oldVersion) {
					return list.subList(i,
							indexOfNewVersionOperation(newVersion));
				}
			}
		}

		return null;
	}

	private int indexOfNewVersionOperation(int newVersion) {
		if (!CollectionUtils.isEmpty(list)) {
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getDatabaseVersion() > newVersion) {
					return i;
				}
			}
		}

		return list.size();
	}

	public List<DatabaseUpgrade> list() {
		return list;
	}
}